<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="课程名称" prop="courseName">
        <el-input v-model="queryParams.courseName" placeholder="请输入课程名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="课程代码" prop="courseCode">
        <el-input v-model="queryParams.courseCode" placeholder="请输入课程代码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否精选" prop="isFeatured">
        <el-select v-model="queryParams.isFeatured" placeholder="请选择是否精选" clearable>
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['course:course:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['course:course:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['course:course:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['course:course:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="课程ID" align="center" prop="id" /> -->
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="课程代码" align="center" prop="courseCode" />
      <el-table-column label="课程图片" align="center" prop="courseImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.courseImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="课程累计参与人数" align="center" prop="participantCount" />
      <el-table-column label="是否精选" align="center" prop="isFeatured" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isFeatured === 1 ? 'success' : 'info'" size="mini">
            {{ scope.row.isFeatured === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="课程标签" align="center" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.tags && scope.row.tags.length > 0">
            <el-tag 
              v-for="(tag, index) in scope.row.tags" 
              :key="index" 
              size="mini" 
              style="margin-right: 5px;"
            >
              {{ tag.tagName }}
            </el-tag>
          </span>
          <span v-else style="color: #ccc;">暂无标签</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['course:course:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['course:course:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-s-operation" @click="handleRelatedBank(scope.row)"
            v-hasPermi="['course:course:edit']">关联题库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改课程信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入课程名称" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="课程代码" prop="courseCode">
          <el-input v-model="form.courseCode" placeholder="请输入课程代码" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="课程详情" prop="courseDetail">
          <el-input v-model="form.courseDetail" type="textarea" placeholder="请输入内容" maxlength="500" show-word-limit />
        </el-form-item>
        <el-form-item label="课程图片" prop="courseImage">
          <image-upload v-model="form.courseImage" :limit="3" />
        </el-form-item>
        <el-form-item label="课程累计参与人数" prop="participantCount">
          <el-input v-model="form.participantCount" placeholder="请输入课程累计参与人数" />
        </el-form-item>
        <el-form-item label="是否精选课程" prop="isFeatured">
          <el-radio-group v-model="form.isFeatured">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课程标签" prop="tags">
          <el-select 
            v-model="selectedTagIds" 
            multiple 
            placeholder="请选择课程标签"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="tag in tagList"
              :key="tag.id"
              :label="tag.tagName"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 关联题库对话框 -->
    <el-dialog :title="'关联题库 - ' + currentCourseInfo.courseName" :visible.sync="relatedBankOpen" width="80%" append-to-body>
      <div style="margin-bottom: 16px;">
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          size="small" 
          @click="handleAddBankRelation"
        >新增关联题库</el-button>
      </div>
      
      <el-table v-loading="bankListLoading" :data="relatedBankList" style="width: 100%">
        <el-table-column prop="bankName" label="题库名称" width="200"></el-table-column>
        <el-table-column prop="bankCode" label="题库代码" width="150"></el-table-column>
        <el-table-column prop="bankDescription" label="题库描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="questionCount" label="题目数量" width="120"></el-table-column>
        <el-table-column prop="isPublic" label="是否公开" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPublic === 1 ? 'success' : 'info'" size="mini">
              {{ scope.row.isPublic === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              style="color: #f56c6c;"
              @click="handleRemoveBankRelation(scope.row)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="relatedBankTotal > 0"
        :total="relatedBankTotal"
        :page.sync="relatedBankQuery.pageNum"
        :limit.sync="relatedBankQuery.pageSize"
        @pagination="handleRelatedBankPagination"
        style="margin-top: 20px;"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="relatedBankOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增题库关联对话框 -->
    <el-dialog title="选择要关联的题库" :visible.sync="addBankRelationOpen" width="70%" append-to-body>
      <el-alert
        title="提示：已关联的题库不会在列表中显示"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 16px;"
      ></el-alert>
      <el-form :model="bankSearchParams" ref="bankSearchForm" size="small" :inline="true" style="margin-bottom: 16px;">
        <el-form-item label="题库名称" prop="bankName">
          <el-input 
            v-model="bankSearchParams.bankName" 
            placeholder="请输入题库名称" 
            clearable 
            @keyup.enter.native="searchAvailableBanks"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="searchAvailableBanks">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetBankSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table 
        v-loading="availableBankListLoading" 
        :data="availableBankList" 
        @selection-change="handleBankSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="bankName" label="题库名称" width="200"></el-table-column>
        <el-table-column prop="bankCode" label="题库代码" width="150"></el-table-column>
        <el-table-column prop="bankDescription" label="题库描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="questionCount" label="题目数量" width="120"></el-table-column>
        <el-table-column prop="isPublic" label="是否公开" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPublic === 1 ? 'success' : 'info'" size="mini">
              {{ scope.row.isPublic === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="availableBankTotal > 0"
        :total="availableBankTotal"
        :page.sync="availableBankSearchQuery.pageNum"
        :limit.sync="availableBankSearchQuery.pageSize"
        @pagination="handleAvailableBankPagination"
        style="margin-top: 20px;"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button 
          type="primary" 
          @click="submitBankRelation" 
          :disabled="selectedBanks.length === 0 || submittingBankRelation"
          :loading="submittingBankRelation"
        >
          {{ submittingBankRelation ? '关联中...' : `确定关联 (${selectedBanks.length})` }}
        </el-button>
        <el-button @click="cancelAddBankRelation" :disabled="submittingBankRelation">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCourse, getCourse, delCourse, addCourse, updateCourse, addTagRelation, getCourseBanks, addCourseBank, removeCourseBank } from "@/api/course/course";
import { listAllCourseTag } from "@/api/course/courseTag";
import { listAllQuestionBank } from "@/api/exam/questionBank";

export default {
  name: "Course",
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程信息表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseName: null,
        courseCode: null,
        courseDetail: null,
        courseImage: null,
        participantCount: null,
        isFeatured: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "课程ID不能为空", trigger: "blur" }
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" },
          { max: 20, message: "课程名称最多20个字符", trigger: "blur" }
        ],
        courseCode: [
          { required: true, message: "课程代码不能为空", trigger: "blur" },
          { max: 20, message: "课程代码最多20个字符", trigger: "blur" }
        ],
        courseDetail: [
          { required: true, message: "课程详情不能为空", trigger: "blur" },
          { max: 500, message: "课程详情最多500个字符", trigger: "blur" }
        ],
        courseImage: [
          { required: true, message: "课程图片不能为空", trigger: "blur" }
        ],
        participantCount: [
          { required: true, message: "课程累计参与人数不能为空", trigger: "blur" }
        ],
        isFeatured: [
          { required: true, message: "请选择是否为精选课程", trigger: "change" }
        ],
      },
      tagList: [],
      // 选中的标签ID数组（用于表单绑定）
      selectedTagIds: [],
      // 关联题库对话框控制变量
      relatedBankOpen: false,
      // 关联题库列表数据
      relatedBankList: [],
      // 关联题库列表加载状态
      bankListLoading: false,
      // 关联题库列表总数
      relatedBankTotal: 0,
      // 关联题库列表查询参数
      relatedBankQuery: {
        pageNum: 1,
        pageSize: 10
      },
      // 当前查看关联题库的课程信息
      currentCourseInfo: {},
      // 新增题库关联对话框控制变量
      addBankRelationOpen: false,
      // 可选题库列表数据
      availableBankList: [],
      // 可选题库列表加载状态
      availableBankListLoading: false,
      // 可选题库列表总数
      availableBankTotal: 0,
      // 可选题库搜索查询参数
      availableBankSearchQuery: {
        pageNum: 1,
        pageSize: 10
      },
      // 题库搜索参数
      bankSearchParams: {
        bankName: null,
        bankCode: null
      },
      // 选中的题库列表
      selectedBanks: [],
      // 提交题库关联状态
      submittingBankRelation: false
    };
  },
  async created() {
    // 先获取标签列表，再获取课程列表
    await this.getTagList();
    this.getList();
  },
  methods: {
    /** 查询课程信息列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTagList() {
      return listAllCourseTag().then(response => {
        if(response.code === 200) {
          this.tagList = response.data;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        courseName: null,
        courseCode: null,
        courseDetail: null,
        courseImage: null,
        participantCount: null,
        isFeatured: 0,
        tags: [],
      };
      this.selectedTagIds = [];
      this.resetForm("form"); 
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCourse(id).then(response => {
        this.form = response.data;
        // 设置选中的标签ID
        if (this.form.tags && this.form.tags.length > 0) {
          this.selectedTagIds = this.form.tags.map(tag => tag.id);
        } else {
          this.selectedTagIds = [];
        }
        this.open = true;
        this.title = "修改课程信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form.tags)
          // 将选中的标签ID转换为ExamCourseTagVo格式
          if (this.form.id != null) {
            // 修改课程
            updateCourse(this.form).then(response => {
              addTagRelation({tagIds:this.selectedTagIds,courseId:this.form.id}).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            });
          } else {
            // 新增课程
            addCourse(this.form).then(response => {
              addTagRelation({tagIds:this.selectedTagIds,courseId:response.data}).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除课程信息编号为"' + ids + '"的数据项？').then(function () {
        return delCourse(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('course/course/export', {
        ...this.queryParams
      }, `course_${new Date().getTime()}.xlsx`)
    },
    // 处理关联题库
    handleRelatedBank(row) {
      this.currentCourseInfo = row;
      this.resetRelatedBankQuery();
      this.getRelatedBankList();
      this.relatedBankOpen = true;
    },
    // 重置关联题库查询参数
    resetRelatedBankQuery() {
      this.relatedBankQuery = {
        pageNum: 1,
        pageSize: 10
      };
    },
    // 获取关联题库列表
    getRelatedBankList() {
      this.bankListLoading = true;
      getCourseBanks(this.currentCourseInfo.id, this.relatedBankQuery).then(response => {
        this.relatedBankList = response.rows;
        this.relatedBankTotal = response.total;
        this.bankListLoading = false;
      }).catch(() => {
        this.bankListLoading = false;
      });
    },
    // 关联题库列表分页
    handleRelatedBankPagination(val) {
      this.relatedBankQuery.pageNum = val.page;
      this.relatedBankQuery.pageSize = val.limit;
      this.getRelatedBankList();
    },
    // 处理新增题库关联
    handleAddBankRelation() {
      this.resetBankSearch();
      this.getAvailableBankList();
      this.addBankRelationOpen = true;
    },
    // 重置题库搜索
    resetBankSearch() {
      this.bankSearchParams = {
        bankName: null,
        bankCode: null
      };
      this.availableBankSearchQuery = {
        pageNum: 1,
        pageSize: 10
      };
      this.selectedBanks = [];
      this.submittingBankRelation = false;
    },
    // 搜索可选题库
    searchAvailableBanks() {
      this.availableBankSearchQuery.pageNum = 1;
      this.getAvailableBankList();
    },
    // 获取可选题库列表
    getAvailableBankList() {
      this.availableBankListLoading = true;
      const queryParams = {
        ...this.availableBankSearchQuery,
        ...this.bankSearchParams
      };
      listAllQuestionBank(queryParams).then(response => {
        let bankList = response.rows || response.data || [];
        
        // 过滤掉已经关联的题库
        const relatedBankIds = this.relatedBankList.map(bank => bank.id);
        bankList = bankList.filter(bank => !relatedBankIds.includes(bank.id));
        
        this.availableBankList = bankList;
        this.availableBankTotal = bankList.length; // 注意：这里使用过滤后的长度
        this.availableBankListLoading = false;
      }).catch(() => {
        this.availableBankListLoading = false;
      });
    },
    // 可选题库列表分页
    handleAvailableBankPagination(val) {
      this.availableBankSearchQuery.pageNum = val.page;
      this.availableBankSearchQuery.pageSize = val.limit;
      this.getAvailableBankList();
    },
    // 题库选择变化
    handleBankSelectionChange(selection) {
      this.selectedBanks = selection;
    },
    // 提交题库关联
    submitBankRelation() {
      if (this.selectedBanks.length === 0) {
        this.$modal.msgWarning("请选择要关联的题库");
        return;
      }
      
      this.submittingBankRelation = true;
      
      // 提取选中题库的ID列表
      const bankIds = this.selectedBanks.map(bank => bank.bankId);
      
      // 调用批量添加接口
      addCourseBank(this.currentCourseInfo.id, bankIds).then(response => {
        this.$modal.msgSuccess(response.msg || `成功关联 ${this.selectedBanks.length} 个题库`);
        this.addBankRelationOpen = false;
        this.getRelatedBankList();
        this.resetBankSearch();
      }).catch(error => {
        console.error("关联题库失败:", error);
        const errorMsg = error.response?.data?.msg || "关联题库失败，请重试";
        this.$modal.msgError(errorMsg);
      }).finally(() => {
        this.submittingBankRelation = false;
      });
    },
    // 取消新增题库关联
    cancelAddBankRelation() {
      this.addBankRelationOpen = false;
      this.resetBankSearch();
    },
    // 移除题库关联
    handleRemoveBankRelation(row) {
      this.$modal.confirm('是否确认移除题库"' + row.bankName + '"的关联？').then(() => {
        return removeCourseBank(this.currentCourseInfo.id, row.bankId);
      }).then(() => {
        this.$modal.msgSuccess("移除题库关联成功");
        this.getRelatedBankList();
      }).catch(() => {});
    }
  }
};
</script>
